package com.tensquare.article.service;

import com.tensquare.article.dao.ArticleDao;
import com.tensquare.article.pojo.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @author Macross
 * @Type ArticleService.java
 * @Desc 文章Service服务类
 * @date 2019/12/17 19:38
 */
@Service
public class ArticleService {

    @Autowired
    private ArticleDao articleDao;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 指定文章审核
     * @param articleId 文章id
     */
    public void examine(String articleId) {
        //更新文章审核状态
        articleDao.updateState(articleId);
    }

    /**
     * 文章点赞数+1
     * @param articleId 文章id
     */
    public void updateThumbup(String articleId) {
        //文章点赞数+1
        articleDao.updateThumbup(articleId);
    }

    /**
     * 获取指定文章的信息
     * @param articleId 文章id
     * @return
     */
    public Article findById(String articleId) {
        //从Redis中获取文章信息
        Article article = (Article) redisTemplate.opsForValue().get("article_" + articleId);
        //判断文章信息是否为空
        if (article == null){
            //从数据库中获取文章信息
            Optional<Article> optionalArticle = articleDao.findById(articleId);
            //获取文章信息
            article = optionalArticle.orElse(null);
            //将文章信息放入Redis,过期时间为10s
            redisTemplate.opsForValue().set("article_"+articleId,article,10, TimeUnit.SECONDS);
        }
        //返回文章信息
        return article;
    }

    /**
     * 修改文章信息,并清除对应的文章缓存
     * @param article 文章信息
     */
    @CacheEvict(value = "article",key = "'article_'+#article.id")
    public void updateArticle(Article article){
        //更新文章信息
        articleDao.save(article);
    }

    /**
     * 删除文章信息,并清除对应的文章缓存
     * @param articleId 文章id
     */
    @CacheEvict(value = "article",key = "'article_'+#articleId")
    public void deleteArticle(String articleId){
        //删除文章信息
        articleDao.deleteById(articleId);
    }
}
